﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Data;
using System.Data.OleDb;
using System.Collections.ObjectModel;
using libConn;
using System.IO;
using CodeReason.Reports;
using System.Windows.Xps.Packaging;
using Microsoft.Win32;

namespace ApartmentSale
{
	public partial class Affirmance : Window
	{
		public Affirmance()
		{
			this.InitializeComponent();
		}

        private bool getData()
        {
            string errMessage = null;
            string str = "SELECT * FROM affirmance ORDER BY receipt_code";

            DataTable oleDT;
            oleDT = libConn.AccdbConn.query(str, ref errMessage);

            if (errMessage != null)
            {
                System.Windows.MessageBox.Show(
                    errMessage,
                    "An error occurred while reading data affirmance.",
                    System.Windows.MessageBoxButton.OK,
                    System.Windows.MessageBoxImage.Error);
                return false;
            }

            ObservableCollection<AffirmanceView> affirmance = new ObservableCollection<AffirmanceView>();

            foreach (DataRow r in oleDT.Rows)
            {
                affirmance.Add(new AffirmanceView()
                {
                    affirmance_id = Convert.ToInt32(r["affirmance_id"]),
                    affirmance_status = Convert.ToInt32(r["affirmance_status"]),
                    receipt_id = Convert.ToInt32(r["receipt_id"]),
                    receipt_code = r["receipt_code"].ToString().Replace("''", "'"),
                    affirmance_amount = Convert.ToDouble(r["affirmance_amount"]),
                    affirmance_rule_type = r["affirmance_rule_type"].ToString().Replace("''", "'"),
                    affirmance_rule_rebate_amount = Convert.ToDouble(r["affirmance_rule_rebate_amount"]),
                    affirmance_custom_name = r["affirmance_custom_name"].ToString().Replace("''", "'"),
                    affirmance_custom_contact = r["affirmance_custom_contact"].ToString().Replace("''", "'"),
                    affirmance_create_date = Convert.ToDateTime(r["affirmance_create_date"])
                });
            }

            dataGrid.DataContext = affirmance;

            return true;
        }

        private bool getData(DateTime begin, DateTime end)
        {
            string errMessage = null;
            string str = "SELECT * FROM affirmance WHERE affirmance_create_date BETWEEN #"
                + begin.ToShortDateString()
                + "# AND #"
                + end.AddDays(1).ToShortDateString()
                + "# ORDER BY receipt_code";

            DataTable oleDT;
            oleDT = libConn.AccdbConn.query(str, ref errMessage);

            if (errMessage != null)
            {
                System.Windows.MessageBox.Show(
                    errMessage,
                    "An error occurred while reading data affirmance.",
                    System.Windows.MessageBoxButton.OK,
                    System.Windows.MessageBoxImage.Error);
                return false; ;
            }

            ObservableCollection<AffirmanceView> affirmance = new ObservableCollection<AffirmanceView>();

            foreach (DataRow r in oleDT.Rows)
            {
                affirmance.Add(new AffirmanceView()
                {
                    affirmance_id = Convert.ToInt32(r["affirmance_id"]),
                    affirmance_status = Convert.ToInt32(r["affirmance_status"]),
                    receipt_id = Convert.ToInt32(r["receipt_id"]),
                    receipt_code = r["receipt_code"].ToString().Replace("''", "'"),
                    affirmance_amount = Convert.ToDouble(r["affirmance_amount"]),
                    affirmance_rule_type = r["affirmance_rule_type"].ToString().Replace("''", "'"),
                    affirmance_rule_rebate_amount = Convert.ToDouble(r["affirmance_rule_rebate_amount"]),
                    affirmance_custom_name = r["affirmance_custom_name"].ToString().Replace("''", "'"),
                    affirmance_custom_contact = r["affirmance_custom_contact"].ToString().Replace("''", "'"),
                    affirmance_create_date = Convert.ToDateTime(r["affirmance_create_date"])
                });
            }

            dataGrid.DataContext = affirmance;

            return true;
        }

        private void btAdd_Click(object sender, RoutedEventArgs e)
        {
            AffirmanceEdit dialog = new AffirmanceEdit();
            dialog.ShowDialog();
            getData();
        }

        private void dataGrid_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            if (dataGrid.SelectedIndex == -1)
                return;

            var affirmence = dataGrid.SelectedItem as AffirmanceView;
            if (affirmence != null)
            {
                AffirmanceEdit dialog = new AffirmanceEdit(affirmence);
                dialog.ShowDialog();
                getData();
            }
        }

        private void btModify_Click(object sender, RoutedEventArgs e)
        {
            if (dataGrid.SelectedIndex == -1)
                return;

            var affirmence = dataGrid.SelectedItem as AffirmanceView;
            if (affirmence != null)
            {
                AffirmanceEdit dialog = new AffirmanceEdit(affirmence);
                dialog.ShowDialog();
                getData();
            }
        }

        private void btDelete_Click(object sender, RoutedEventArgs e)
        {
            if (dataGrid.SelectedIndex == -1)
                return;

            var affirmance = dataGrid.SelectedItem as AffirmanceView;
            if (affirmance != null)
            {
                if (affirmance.affirmance_status == 1)
                {
                    System.Windows.MessageBox.Show(
                        "The current amount of affirmance have been offset back the principal.",
                        "Remove prohibited",
                        System.Windows.MessageBoxButton.OK,
                        System.Windows.MessageBoxImage.Stop);
                    return;
                }

                if (MessageBox.Show("Do you want to delete this record?\nThis action can not be recovered!",
                    "Remove", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.No)
                    return;

                string errMessage = null;
                string str = "DELETE FROM affirmance WHERE affirmance_id = " + affirmance.affirmance_id;

                libConn.AccdbConn.exec(str, ref errMessage);

                if (errMessage != null)
                {
                    System.Windows.MessageBox.Show(
                        errMessage,
                        "Failed to delete record affirmance.",
                        System.Windows.MessageBoxButton.OK,
                        System.Windows.MessageBoxImage.Error);
                    return;
                }

                str = "DELETE FROM receipt WHERE receipt_id = " + affirmance.receipt_id;

                libConn.AccdbConn.exec(str, ref errMessage);

                if (errMessage != null)
                {
                    System.Windows.MessageBox.Show(
                        errMessage,
                        "Failed to delete record affirmance.",
                        System.Windows.MessageBoxButton.OK,
                        System.Windows.MessageBoxImage.Error);
                    return;
                }

                getData();
            }

        }

        private void btQuery_Click(object sender, RoutedEventArgs e)
        {
            if (dpBegin.SelectedDate == null || dpEnd.SelectedDate == null)
            {
                getData();
                return;
            }

            if (dpBegin.SelectedDate > dpEnd.SelectedDate)
            {
                MessageBox.Show("Deadline is not until the start date.");
                dpEnd.Focus();
                return;
            }

            getData((DateTime)dpBegin.SelectedDate, (DateTime)dpEnd.SelectedDate);

        }

        private void btClose_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        private void affirmance_Loaded(object sender, RoutedEventArgs e)
        {
            if (!getData())
                this.Close();
        }

        private DataTable GetDataTable()
        {
            DataTable table = new DataTable("Data Table");

            DataColumn column;
            DataRow row;

            column = new DataColumn();
            column.DataType = Type.GetType("System.String");
            column.ColumnName = "code";
            column.Caption = "Receipt SN";
            column.ReadOnly = true;
            column.Unique = true;
            table.Columns.Add(column);

            column = new DataColumn();
            column.DataType = Type.GetType("System.String");
            column.ColumnName = "status";
            column.AutoIncrement = false;
            column.Caption = "Status";
            column.ReadOnly = false;
            column.Unique = false;
            table.Columns.Add(column);

            column = new DataColumn();
            column.DataType = Type.GetType("System.String");
            column.ColumnName = "amount";
            column.AutoIncrement = false;
            column.Caption = "Amount";
            column.ReadOnly = false;
            column.Unique = false;
            table.Columns.Add(column);


            column = new DataColumn();
            column.DataType = Type.GetType("System.String");
            column.ColumnName = "type";
            column.AutoIncrement = false;
            column.Caption = "Type";
            column.ReadOnly = false;
            column.Unique = false;
            table.Columns.Add(column);

            column = new DataColumn();
            column.DataType = Type.GetType("System.String");
            column.ColumnName = "name";
            column.AutoIncrement = false;
            column.Caption = "Custom Name";
            column.ReadOnly = false;
            column.Unique = false;
            table.Columns.Add(column);

            column = new DataColumn();
            column.DataType = Type.GetType("System.String");
            column.ColumnName = "contact";
            column.AutoIncrement = false;
            column.Caption = "Contract";
            column.ReadOnly = false;
            column.Unique = false;
            table.Columns.Add(column);

            column = new DataColumn();
            column.DataType = Type.GetType("System.String");
            column.ColumnName = "date";
            column.AutoIncrement = false;
            column.Caption = "Date";
            column.ReadOnly = false;
            column.Unique = false;
            table.Columns.Add(column);

            DataColumn[] PrimaryKeyColumns = new DataColumn[1];
            PrimaryKeyColumns[0] = table.Columns["code"];
            table.PrimaryKey = PrimaryKeyColumns;

            foreach (AffirmanceView affirmance in dataGrid.Items)
            {
                row = table.NewRow();
                row["code"] = affirmance.receipt_code;
                row["status"] = affirmance.status_string;
                row["amount"] = affirmance.affirmance_amount.ToString("0.00");
                row["type"] = affirmance.rule_string;
                row["name"] = affirmance.affirmance_custom_name;
                row["contact"] = affirmance.affirmance_custom_contact;
                row["date"] = affirmance.date_string;
                table.Rows.Add(row);
            }

            return table;
        }

        private void btPrint_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                this.Cursor = Cursors.AppStarting;
                ReportDocument reportDocument = new ReportDocument();

                StreamReader reader = new StreamReader(new FileStream(@"Templates\AffirmanceReport.xaml", FileMode.Open, FileAccess.Read));
                reportDocument.XamlData = reader.ReadToEnd();
                reportDocument.XamlImagePath = System.IO.Path.Combine(Environment.CurrentDirectory, @"Templates\");
                reader.Close();

                ReportData data = new ReportData();

                data.ReportDocumentValues.Add("PrintDate", DateTime.Now);

                DataTable table = GetDataTable();

                data.DataTables.Add(table);

                XpsDocument xps = reportDocument.CreateXpsDocument(data);

                ReportPreview dialog = new ReportPreview();
                dialog.DocView.Document = xps.GetFixedDocumentSequence();

                dialog.Title = "Affirmance";

                this.Cursor = Cursors.Arrow;
                dialog.ShowDialog();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + "\r\n\r\n" + ex.GetType() + "\r\n" + ex.StackTrace, ex.GetType().ToString(), MessageBoxButton.OK, MessageBoxImage.Stop);
            }
        }
	}
}